package img

import (
	"errors"
	"image"
	"image/gif"
	"image/jpeg"
	"image/png"
	"os"

	"github.com/nfnt/resize"
	"golang.org/x/image/bmp"
)

var maxWidth uint = 750

// GetImageThumb 得到图片的缩略图
func GetImageThumb(src string, dst string, width, height uint, quality int) (thumb string, err error) {
	fOut, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE, os.ModePerm)
	if err != nil {
		return
	}
	defer fOut.Close()

	fIn, _ := os.Open(src)
	defer fIn.Close()

	origin, fm, err := image.Decode(fIn)
	if err != nil {
		return
	}
	if width == 0 || height == 0 {
		width = uint(origin.Bounds().Max.X)
		height = uint(origin.Bounds().Max.Y)
	}
	if width > maxWidth {
		height = height * width / maxWidth
		width = maxWidth
	}
	if quality <= 0 {
		quality = 80
	}
	canvas := resize.Thumbnail(width, height, origin, resize.Bilinear)

	switch fm {
	case "jpeg":
		err = jpeg.Encode(fOut, canvas, &jpeg.Options{
			Quality: quality,
		})
	case "png":
		err = png.Encode(fOut, canvas)
	case "gif":
		err = gif.Encode(fOut, canvas, &gif.Options{})
	case "bmp":
		err = bmp.Encode(fOut, canvas)
	default:
		err = errors.New("ERROR FORMAT")
		return
	}

	if err == nil {
		thumb = dst
	}

	return
}

const maxWidthDefault = 750

// Compress 压缩图片
func Compress(src string, dst string, width, height uint, quality int, maxWidth uint) (thumb string, e error) {
	fOut, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE, os.ModePerm)
	if err != nil {
		return
	}
	defer fOut.Close()

	fIn, _ := os.Open(src)
	defer fIn.Close()

	origin, _, err := image.Decode(fIn)
	if err != nil {
		return
	}
	if width == 0 || height == 0 {
		width = uint(origin.Bounds().Max.X)
		height = uint(origin.Bounds().Max.Y)
	}
	if maxWidth > 0 && maxWidth < 10 {
		maxWidth = maxWidthDefault
	}

	// fmt.Println("maxWidth = ", maxWidth)
	if maxWidth > 0 && width > maxWidth {
		height = height * width / maxWidth
		width = maxWidth
	}
	if quality == 0 {
		quality = 80
	}
	// fmt.Println(width, height, quality)
	canvas := resize.Thumbnail(width, height, origin, resize.Bilinear)
	e = jpeg.Encode(fOut, canvas, &jpeg.Options{
		Quality: quality,
	})
	if e != nil {
		return
	}

	return
}
